package com.blog.cloud.chat.utils;

import com.alibaba.fastjson2.JSONObject;
import com.blog.cloud.chat.message.Message;
import com.blog.cloud.chat.message.chat.SendToSingleMessage;
import jakarta.websocket.RemoteEndpoint;
import jakarta.websocket.Session;
import lombok.SneakyThrows;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketUtil {

    public static final Map<String, Session> USER_SESSION_MAP = new ConcurrentHashMap<>();

    public static final Map<Session, String> SESSION_USER_MAP = new ConcurrentHashMap<>();

    public static void addSession(Session session, String userId) {
        USER_SESSION_MAP.put(userId, session);
        SESSION_USER_MAP.put(session, userId);
    }

    public static void removeSession(String userId) {
        Session session = USER_SESSION_MAP.remove(userId);
        SESSION_USER_MAP.remove(session);
    }


    /**
     * 客户端发消息后的响应
     *
     * @param session 会话
     * @param type    消息类型
     * @param message 消息
     * @param <T>     消息类型约束
     */
    public static <T extends Message> void sendResponse(Session session, String type, T message) {
        String text = buildMessage(type, message);
        send(session, text);
    }

    @SneakyThrows
    private static void send(Session session, String text) {
        RemoteEndpoint.Basic basic = session.getBasicRemote();
        basic.sendText(text);
    }

    private static <T extends Message> String buildMessage(String type, T message) {
        JSONObject object = new JSONObject();
        object.put("type", type);
        object.put("message", message);
        return object.toString();
    }

    public static void sendToSingle(String userId, String type, SendToSingleMessage message) {
        Session session = USER_SESSION_MAP.get(userId);
        String text = buildMessage(type, message);
        send(session, text);
    }
}
